home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 10 / AACD 10.iso / AACD / Online / SpeakFreely / src / mike.c < prev    next >
C/C++ Source or Header  |  2000-05-18  |  67KB  |  2,333 lines

  1. #define USE_CURSES
  2. #define BYTE_SWAP_DEBUG
  3. /*
  4.  
  5.             Speak Freely for Unix
  6.           Network sound transmission program
  7.  
  8.     Designed and implemented in July of 1991 by John Walker
  9.  
  10. */
  11.  
  12. #include "speakfree.h"
  13. #include "version.h"
  14.  
  15. /*  Destination host descriptor.  */
  16.  
  17. struct destination {
  18.     struct destination *dnext;          /* Next destination in list */
  19.     char *server;              /* Host name identifier string */
  20.     struct sockaddr_in name;          /* Internet address */
  21.     struct sockaddr_in ctrl;          /* RTCP port address */
  22.     unsigned char time_to_live;       /* Multicast scope specification */
  23.     char deskey[9];              /* Destination DES key, if any */
  24.     char rtpdeskey[9];              /* Destination RTP DES key, if any */
  25.     char vatdeskey[9];              /* Destination VAT DES key, if any */
  26.     char ideakey[17];              /* Destination IDEA key, if any */
  27.     char pgpkey[17];              /* Destination PGP key, if any */
  28.     char blowfish_spec;           /* Nonzero if Blowfish key specified */
  29. #ifdef CRYPTO
  30.     BF_KEY blowfishkey;           /* Destination Blowfish key, if any */
  31. #endif
  32.     char *otp;                  /* Key file */
  33. };
  34.  
  35. static char *progname;              /* Program name */
  36. static int sock;              /* Communication socket */
  37. static struct destination *dests = NULL, *dtail;
  38. static int compressing = FALSE;       /* Compress sound: simple 2X */
  39. static int gsmcompress = TRUE;          /* GSM compress buffers */
  40. #ifdef OBSOLETE
  41. static int gsm_byte_order_kludge = TRUE; /* Transition to correct byte order for GSM ? */
  42. #endif
  43. #ifdef BYTE_SWAP_DEBUG
  44. static int gsm_byte_order_debug = FALSE; /* Send GSM length field with swapped bytes */
  45. #endif
  46. static int lpccompress = FALSE;       /* LPC compress buffers */
  47. static int lpc10compress = FALSE;     /* LPC-10 compress buffers */
  48. static int adpcmcompress = FALSE;     /* ADPCM compress buffers */
  49. static int toasted = FALSE;          /* Sending already-compressed file ? */
  50. static int robust = 1;              /* Robust duplicate packets mode */
  51. static int rseq = 0;              /* Robust mode packet sequence number */
  52.  
  53. #define DEFAULT_SQUELCH 4096          /* Default squelch level */
  54. static int squelch = 0;           /* Squelch level if > 0 */
  55. static int sqdelay = 12000;          /* Samples to delay before squelch */
  56. static int sqwait = 0;              /* Squelch delay countdown */
  57. #ifdef PUSH_TO_TALK
  58. static int push = TRUE;           /* Push to talk mode */
  59. static int talking = FALSE;          /* Push to talk button state */
  60. static int rawmode = FALSE;          /* Is terminal in raw mode ? */
  61. #endif
  62. static int ring = FALSE;          /* Force speaker & level on next pkt ? */
  63. static int rtp = FALSE;           /* Use Internet Real-Time Protocol */
  64. static int vat = FALSE;           /* Use VAT protocol */
  65. static int agc = FALSE;           /* Automatic gain control active ? */
  66. static int rgain = 33;              /* Current recording gain level */
  67. static int spurt = TRUE;          /* True for first packet of talk spurt */
  68. static int debugging = FALSE;          /* Debugging enabled here and there ? */
  69. static FILE *audioDumpFile = NULL;    /* Audio dump file, if any */
  70. static int havesound = FALSE;         /* True if we've acquired sound input */
  71. static char hostname[20];          /* Host name to send with packets */
  72. static int loopback = FALSE;          /* Remote loopback mode */
  73. static gsm gsmh;              /* GSM handle */
  74. static struct adpcm_state adpcm = {0, 0}; /* ADPCM compression state */
  75.  
  76. static char *vatid = NULL;          /* VAT ID packet */
  77. static int vatidl;              /* VAT ID packet length */
  78.  
  79. static unsigned long ssrc;          /* RTP synchronisation source identifier */
  80. static unsigned long timestamp;       /* RTP packet timestamp */
  81. static unsigned short seq;          /* RTP packet sequence number */
  82. static unsigned long rtpdesrand;      /* RTP DES random RTCP prefix */
  83.  
  84. static char *sdes = NULL;          /* RTP SDES packet */
  85. static int sdesl;              /* RTP SDES packet length */
  86.  
  87. static char curkey[9] = "";           /* Current DES key if curkey[0] != 0 */
  88. static char currtpkey[9] = "";        /* Current RTP DES key if currtpkey[0] != 0 */
  89. static char curvatkey[9] = "";        /* Current VAT DES key if currtpkey[0] != 0 */
  90. static char curideakey[17] = "";      /* Current IDEA key if curideakey[0] != 0 */
  91. static char curpgpkey[17] = "";       /* Current PGP key if curpgpkey[0] != 0 */
  92. static char curblowfish_spec = FALSE; /* Nonzero if Blowfish key specified */
  93. #ifdef CRYPTO
  94. static BF_KEY curblowfishkey;          /* Blowfish key */
  95. #endif
  96. static char *curotp = NULL;          /* Key file buffer */
  97. static int sound_packet;          /* Ideal samples/packet */
  98. static struct soundbuf *pgpsb = NULL; /* PGP key sound buffer, if any */
  99. static LONG pgpsbl;              /* Length of PGP key sound buffer data */
  100. #ifdef HALF_DUPLEX
  101. static struct in_addr localhost;      /* Our internet address */
  102. static int halfDuplexMuted = FALSE;   /* Muted by half-duplex transmission */
  103. #endif
  104. static int hasFace = FALSE;          /* Is a face image available ? */
  105.  
  106. #ifdef sgi
  107. static long usticks;              /* Microseconds per clock tick */
  108. #endif
  109.  
  110. #define TimerStep   (7 * 1000000L)    /* Alarm interval in microseconds */
  111.  
  112. #ifdef HEWLETT_PACKARD
  113. extern int HPTermHookChar;
  114. #endif
  115.  
  116. /* Audio input and control device file names. */
  117.  
  118. #ifdef AUDIO_DEVICE_FILE
  119. extern char *devAudioInput, *devAudioControl;
  120. #endif
  121.  
  122. #define ucase(x)    (islower(x) ? toupper(x) : (x))
  123.  
  124. #ifndef USE_CURSES
  125.  
  126. #ifndef UNIX420
  127. #define UNIX5
  128. #endif
  129.  
  130. #ifdef UNIX420
  131. #include <sgtty.h>
  132. #endif /* UNIX420 */
  133.  
  134. #ifdef UNIX5
  135. #include <termio.h>
  136. static struct termio old_term_params;
  137. #endif /* UNIX5 */
  138.  
  139. /* Set raw mode on terminal file.  Basically, get the terminal into a
  140.    mode in which all characters can be read as they are entered.  CBREAK
  141.    mode is not sufficient.  */
  142.  
  143. static void tty_rawmode()
  144. {
  145. #ifdef UNIX420
  146.    struct sgttyb arg;
  147.  
  148.    ioctl(fileno(stdin), TIOCGETP, &arg);      /* get basic parameters */
  149.    arg.sg_flags |= RAW;           /* set raw mode */
  150.    arg.sg_flags &= ~ECHO;          /* clear echo mode */
  151.    ioctl(fileno(stdin), TIOCSETP, &arg);      /* set it */
  152. #endif /* UNIX420 */
  153.  
  154. #ifdef UNIX5
  155.    struct termio term_params;
  156.  
  157.    ioctl(fileno(stdin), TCGETA, &old_term_params);
  158.    term_params = old_term_params;
  159.    term_params.c_iflag &= ~(ICRNL|IXON|IXOFF);    /* no cr translation */
  160.    term_params.c_iflag &= ~(ISTRIP);   /* no stripping of high order bit */
  161.    term_params.c_oflag &= ~(OPOST);    /* no output processing */
  162.    term_params.c_lflag &= ~(ISIG|ICANON|ECHO); /* raw mode */
  163.    term_params.c_cc[4] = 1;  /* satisfy read after 1 char */
  164.    ioctl(fileno(stdin), TCSETAF, &term_params);
  165. #endif /* UNIX5 */
  166. /*printf("\n(raw)\n");*/
  167. }
  168.  
  169. /* Restore tty mode */
  170.  
  171. static void tty_normode()
  172. {
  173. #ifdef UNIX420
  174. struct sgttyb arg;
  175.  
  176.    ioctl(fileno(stdin), TIOCGETP, &arg);      /* get basic parameters */
  177.    arg.sg_flags &= ~RAW;          /* clear raw mode */
  178.    arg.sg_flags |= ECHO;          /* set echo mode */
  179.    ioctl(fileno(stdin), TIOCSETP, &arg);      /* set it */
  180. #endif /* UNIX420 */
  181.  
  182. #ifdef UNIX5
  183.    ioctl(fileno(stdin), TCSETAF, &old_term_params);
  184. #endif /* UNIX5 */
  185. /*printf("\n(cooked)\n");*/
  186. }
  187. #endif
  188.  
  189. /*  ULARM  --  Wrapper for setitimer() that looks like alarm()
  190.            but accepts a time in microseconds.  */
  191.  
  192. static void ularm(t)
  193.   long t;
  194. {
  195.     struct itimerval it;
  196.  
  197.     it.it_value.tv_sec = t / 1000000L;
  198.     it.it_value.tv_usec = t % 1000000L;
  199.     it.it_interval.tv_sec = it.it_interval.tv_usec = 0;
  200.     setitimer(ITIMER_REAL, &it, NULL);
  201. }
  202.  
  203. /*  GSMCOMP  --  Compress the contents of a sound buffer using GSM.  */
  204.  
  205. static void gsmcomp(sb)
  206.   struct soundbuf *sb;
  207. {
  208.     gsm_signal src[160];
  209.     gsm_frame dst;
  210.     int i, j, l = 0;
  211.     char *dp = ((char *) sb->buffer.buffer_val) + sizeof(short);
  212.  
  213.     sb->compression |= fCompGSM;
  214.     for (i = 0; i < sb->buffer.buffer_len; i += 160) {
  215.     for (j = 0; j < 160; j++) {
  216.         if ((i + j) < sb->buffer.buffer_len) {
  217.         src[j] = audio_u2s(sb->buffer.buffer_val[i + j]);
  218.         } else {
  219.         src[j] = 0;
  220.         }
  221.     }
  222.     gsm_encode(gsmh, src, dst);
  223.     bcopy(dst, dp, sizeof dst);
  224.     dp += sizeof dst;
  225.     l += sizeof dst;
  226.     }
  227.  
  228.     /* Hide original uncompressed buffer length in first 2 bytes of buffer. */
  229.  
  230. #ifdef OBSOLETE
  231.  
  232.     /* Allow me to explain the following if statement.    Speak
  233.        Freely for Unix prior to release 6.1e contained a bug
  234.        which caused it to both send (here) and receive
  235.        (in speaker.c) GSM packets with the embedded length
  236.        in host byte order.  This went undetected for a long
  237.        time because all the Unix machines I have access to
  238.        for testing are big-endian and thus interoperated
  239.        correctly with one another and the Windows version
  240.        (which does handle the byte order correctly).  Many
  241.        Linux and FreeBSD users only speak to one another,
  242.        and thus never noticed the problem.  It was only when
  243.        a little-endian Unix machine attempted to use GSM
  244.        compression in a connection with a Windows or
  245.        big-endian Unix machine that what came to be called
  246.        the "deafening static" problem manifested itself.
  247.        The fix is obvious, but we have to get there in
  248.        a cautious manner to avoid breaking interoperability
  249.        during the transition.  So here's the plan: starting
  250.        with Unix release 6.1e and the corresponding Windows
  251.        release, the GSM receiving code in both versions
  252.        will accept the GSM packet length field in
  253.        *either* byte order (a byte-swapped value in this
  254.        field can be detected unambiguously because if
  255.        byte-swapped it will exceed the actual length of
  256.        the packet, which is otherwise impossible).  Users
  257.        who install these releases will be able to receive
  258.        GSM sound from any version of Speak Freely on any
  259.        platform, present or future.  Version 6.1e for
  260.        Unix will, however, continue to send the GSM length
  261.        field in host byte order.  Why?    Because otherwise
  262.        Linux and FreeBSD users who communicate with one
  263.        another would both have to install 6.1e before
  264.        they could communicate once again.  To make the
  265.        transition smoother, 6.1e offers a "-tc" option,
  266.        which causes the GSM length field to be sent
  267.        in the correct byte order.  This option should be
  268.        set whenever a Unix user wishes to communicate
  269.        with a Windows user in GSM mode.  It will also
  270.        fix connections to big-endian Unix versions
  271.        prior to 6.1e.  Once a majority of the installed
  272.        base is on the versions which don't care about
  273.        byte order in this field, sending in network byte
  274.        order will be the default.  */
  275.  
  276.     if (gsm_byte_order_kludge) {
  277. #endif
  278.     *((short *) sb->buffer.buffer_val) = htons((short) sb->buffer.buffer_len);
  279. #ifdef OBSOLETE
  280.     } else {
  281.     *((short *) sb->buffer.buffer_val) = sb->buffer.buffer_len;
  282.     }
  283. #endif
  284. #ifdef BYTE_SWAP_DEBUG
  285.     if (gsm_byte_order_debug) {
  286.     unsigned char *bsp = (unsigned char *) sb->buffer.buffer_val;
  287.  
  288.     bsp[0] = sb->buffer.buffer_len & 0xFF;
  289.     bsp[1] = (sb->buffer.buffer_len >> 8) & 0xFF;
  290.     }
  291. #endif
  292.     sb->buffer.buffer_len = l + sizeof(short);
  293. }
  294.  
  295. /*  ADPCMCOMP  --  Compress the contents of a sound buffer using ADPCM.  */
  296.  
  297. static void adpcmcomp(sb)
  298.   struct soundbuf *sb;
  299. {
  300.     unsigned char *dp = (unsigned char *) sb->buffer.buffer_val;
  301.     struct adpcm_state istate;
  302.  
  303.     istate = adpcm;
  304.     sb->compression |= fCompADPCM;
  305.     adpcm_coder_u(dp, (char *) dp, sb->buffer.buffer_len, &adpcm);
  306.     sb->buffer.buffer_len /= 2;
  307.  
  308.     /* Hide the ADPCM encoder state at the end of this buffer.
  309.        The shifting and anding makes the code byte-order
  310.        insensitive. */
  311.  
  312.     dp += sb->buffer.buffer_len;
  313.     *dp++ = ((unsigned int) istate.valprev) >> 8;
  314.     *dp++ = istate.valprev & 0xFF;
  315.     *dp = istate.index;
  316.     sb->buffer.buffer_len += 3;
  317. }
  318.  
  319. /*  LPCCOMP  --  Compress the contents of a sound buffer using LPC.  */
  320.  
  321. static void lpccomp(sb)
  322.   struct soundbuf *sb;
  323. {
  324.     int i, l = 0;
  325.     char *dp = ((char *) sb->buffer.buffer_val) + sizeof(short);
  326.     unsigned char *src = ((unsigned char *) sb->buffer.buffer_val);
  327.     lpcparams_t lp;
  328.  
  329.     sb->compression |= fCompLPC;
  330.     for (i = 0; i < sb->buffer.buffer_len; i += LPC_FRAME_SIZE) {
  331.     lpc_analyze(src + i, &lp);
  332.     bcopy(&lp, dp, LPCRECSIZE);
  333.     dp += LPCRECSIZE;
  334.     l += LPCRECSIZE;
  335.     }
  336.  
  337.     /* Hide original uncompressed buffer length in first 2 bytes of buffer. */
  338.  
  339.     *((short *) sb->buffer.buffer_val) = htons((short) sb->buffer.buffer_len);
  340.     sb->buffer.buffer_len = l + sizeof(short);
  341. }
  342.  
  343. /*  LPC10COMP  --  Compress the contents of a sound buffer using LPC-10.  */
  344.  
  345. static void lpc10comp(sb)
  346.   struct soundbuf *sb;
  347. {
  348.     char *dp = (char *) sb->buffer.buffer_val;
  349.     unsigned char *src = ((unsigned char *) sb->buffer.buffer_val);
  350.  
  351.     sb->compression |= fCompLPC10;
  352.     sb->buffer.buffer_len = lpc10encode(src, dp, sb->buffer.buffer_len);
  353. }
  354.  
  355. /*  LPC10STUFF    --  Stuff last 16 bytes of LPC10 packet in sendinghost. */
  356.  
  357. static int lpc10stuff(sb, pktlen)
  358.   struct soundbuf *sb;
  359.   int pktlen;
  360. {
  361.     if ((sb->compression & fCompLPC10) && (sb->buffer.buffer_len > 16)) {
  362.     bcopy(((char *) sb) + (pktlen - (sizeof sb->sendinghost)),
  363.         sb->sendinghost, sizeof sb->sendinghost);
  364.     pktlen -= sizeof sb->sendinghost;
  365.     }
  366.     return pktlen;
  367. }
  368.  
  369. /*  SENDRTPCTRL  --  Send RTP or VAT control message, encrypting if
  370.              necessary.  */
  371.  
  372. static int sendrtpctrl(d, destaddr, msg, msgl, rtppkt)
  373.   struct destination *d;
  374.   struct sockaddr *destaddr;
  375.   char *msg;
  376.   int msgl, rtppkt;
  377. {
  378.     char aux[1024];
  379.  
  380. #ifdef CRYPTO
  381.     if ((rtp || vat) && d->rtpdeskey[0]) {
  382.     int vlen;
  383.     des_cblock key;
  384.     des_key_schedule sched;
  385.     des_cblock ivec;
  386.  
  387.     bzero(ivec, 8);
  388.  
  389.     if (rtppkt) {
  390.  
  391.         /* Encrypted RTCP messages are prefixed with 4 random
  392.            bytes to prevent known plaintext attacks. */
  393.  
  394.         bcopy(&rtpdesrand, aux, 4);
  395.         bcopy(msg, aux + 4, msgl);
  396.         msgl += 4;
  397.     } else {
  398.         bcopy(msg, aux, msgl);
  399.     }
  400.  
  401.         /* If we're DES encrypting we must round the size of
  402.        the data to be sent to be a multiple of 8 so that
  403.        the entire DES frame is sent.  This applies only to
  404.        VAT, as the code that creates RTCP packets guarantees
  405.            they're already padded to a multiple of 8 bytes. */
  406.  
  407.     vlen = msgl;
  408.     msgl = (msgl + 7) & (~7);
  409.     if (msgl > vlen) {
  410.         bzero(aux + vlen, msgl - vlen);
  411.     }
  412.     if (debugging) {
  413.             fprintf(stderr, "Encrypting %d VAT/RTP bytes with DES key.\r\n",
  414.             msgl);
  415.     }
  416.     des_set_key((des_cblock *) ((rtppkt ? d->rtpdeskey : d->vatdeskey) + 1), sched);
  417.     des_ncbc_encrypt((des_cblock *) aux,
  418.         (des_cblock *) aux, msgl, sched,
  419.         (des_cblock *) ivec, DES_ENCRYPT);
  420.     msg = aux;
  421.     }
  422. #endif
  423.     return sendto(sock, msg, msgl, 0, destaddr, sizeof d->ctrl);
  424. }
  425.  
  426. /*  ADDEST  --    Add destination host to host list.  */
  427.  
  428. static int addest(host)
  429.   char *host;
  430. {
  431.     struct destination *d;
  432.     struct hostent *h;
  433.     long naddr;
  434.     unsigned int ttl = 1;
  435.     char *mcs;
  436.     int curport = Internet_Port;
  437.  
  438.     /* If a multicast scope descriptor appears in the name, scan
  439.        it and lop it off the end.  We'll apply it later if we discover
  440.        this is actually a multicast address. */
  441.  
  442.     if ((mcs = strrchr(host, '/')) != NULL &&
  443.         ((strchr(host, ':') != NULL) || (mcs != strchr(host, '/')))) {
  444.     *mcs = 0;
  445. #ifdef MULTICAST
  446.     ttl = atoi(mcs);
  447. #endif
  448.     }
  449.  
  450.     /* If a port number appears in the name, scan it and lop
  451.        it off.    We allow a slash as well as the documented colon
  452.        as the delimiter to avoid confusing users familiar with
  453.        VAT. */
  454.  
  455.     if ((mcs = strrchr(host, ':')) != NULL ||
  456.         (mcs = strrchr(host, '/')) != NULL) {
  457.     *mcs++ = 0;
  458.     curport = atoi(mcs);
  459.     }
  460.  
  461.     /* If it's a valid IP number, use it.  Otherwise try to look
  462.        up as a host name. */
  463.  
  464.     if ((naddr = inet_addr(host)) != -1) {
  465.     } else {
  466.     h = gethostbyname(host);
  467.     if (h == 0) {
  468.             fprintf(stderr, "%s: unknown host\n", host);
  469.         return FALSE;
  470.     }
  471.     bcopy((char *) h->h_addr, (char *) &naddr, sizeof naddr);
  472.     }
  473.  
  474. #ifdef MULTICAST
  475.     if (!IN_MULTICAST(naddr)) {
  476.     ttl = 0;
  477.     }
  478. #endif
  479.  
  480.     d = (struct destination *) malloc(sizeof(struct destination));
  481.     d->dnext = NULL;
  482.     d->server = host;
  483.     bcopy((char *) &naddr, (char *) &(d->name.sin_addr), sizeof naddr);
  484.     bcopy((char *) &naddr, (char *) &(d->ctrl.sin_addr), sizeof naddr);
  485.     bcopy(curkey, d->deskey, 9);
  486.     bcopy(currtpkey, d->rtpdeskey, 9);
  487.     bcopy(curvatkey, d->vatdeskey, 9);
  488.     bcopy(curideakey, d->ideakey, 17);
  489.     bcopy(curpgpkey, d->pgpkey, 17);
  490.     d->blowfish_spec = curblowfish_spec;
  491. #ifdef CRYPTO
  492.     bcopy(&curblowfishkey, &(d->blowfishkey), sizeof(BF_KEY));
  493. #endif
  494.     d->otp = curotp;
  495.     d->time_to_live = ttl;
  496.     d->name.sin_family = AF_INET;
  497.     d->name.sin_port = htons(curport);
  498.     d->ctrl.sin_family = AF_INET;
  499.     d->ctrl.sin_port = htons(curport + 1);
  500.     if (dests == NULL) {
  501.     dests = d;
  502.     } else {
  503.     dtail->dnext = d;
  504.     }
  505.     dtail = d;
  506.  
  507.     /* Send initial status and identity message in
  508.        the correct protocol. */
  509.  
  510.     if (rtp) {
  511.     if (sendrtpctrl(d, (struct sockaddr *) &(d->ctrl),
  512.             sdes, sdesl, TRUE) < 0) {
  513.             perror("sending initial RTCP SDES packet");
  514.         return FALSE;
  515.     }
  516.     } else if (vat) {
  517.     if (sendrtpctrl(d, (struct sockaddr *) &(d->ctrl),
  518.                vatid, vatidl, FALSE) < 0) {
  519.             perror("sending initial VAT ID control packet");
  520.         return FALSE;
  521.     }
  522.     } else {
  523.     char pid = sdes[0];
  524.  
  525.     /* Set Speak Freely protocol flag in packet */
  526.     sdes[0] = (sdes[0] & 0x3F) | (1 << 6);
  527.     if (sendrtpctrl(d, (struct sockaddr *) &(d->ctrl),
  528.             sdes, sdesl, TRUE) < 0) {
  529.             perror("sending initial Speak Freely SDES control packet");
  530.         return FALSE;
  531.     }
  532.     sdes[0] = pid;
  533.     }
  534.  
  535. #ifdef CRYPTO
  536.     if (pgpsb != NULL) {
  537.     int i;
  538.  
  539.         /* "What I tell you three times is true".  When we change
  540.        over to a TCP connection bracketing the UDP sound data
  541.        transmission, we can send this just once, knowing it has
  542.        arrived safely. */
  543.  
  544.     for (i = 0; i < 3; i++) {
  545.         if (sendto(sock, (char *) pgpsb, (sizeof(struct soundbuf) - BUFL) + pgpsbl,
  546.         0, (struct sockaddr *) &(d->name), sizeof d->name) < 0) {
  547.                 perror("sending PGP session key");
  548.         break;
  549.         }
  550.     }
  551. /* No need to sleep once ack from far end confirms key decoded. */
  552. sleep(7);
  553.     }
  554. #endif
  555.     return TRUE;
  556. }
  557.  
  558. /*  TIMERTICK  --  Timer tick signal-catching function.  */
  559.  
  560. static void timertick()
  561. {
  562.     struct destination *d;
  563.  
  564.     for (d = dests; d != NULL; d = d->dnext) {
  565. #ifdef MULTICAST
  566.     if (IN_MULTICAST(d->name.sin_addr.s_addr)) {
  567.         setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL,
  568.         (char *) &(d->time_to_live), sizeof d->time_to_live);
  569.         if (debugging) {
  570.                 fprintf(stderr, "Multicasting ID/SDES with scope of %d to %s.\n",
  571.             d->time_to_live, inet_ntoa(d->name.sin_addr));
  572.         }
  573.     }
  574. #endif
  575.     if (rtp) {
  576.         if (sendrtpctrl(d, (struct sockaddr *) &(d->ctrl),
  577.              sdes, sdesl, TRUE) < 0) {
  578.                 perror("sending RTCP SDES packet");
  579.         }
  580.     } else if (vat) {
  581.         if (sendrtpctrl(d, (struct sockaddr *) &(d->ctrl),
  582.             vatid, vatidl, FALSE) < 0) {
  583.                 perror("sending VAT ID control packet");
  584.         }
  585.     } else {
  586.         char pid = sdes[0];
  587.  
  588.         /* Set Speak Freely protocol flag in packet */
  589.         sdes[0] = (sdes[0] & 0x3F) | (1 << 6);
  590.         if (sendrtpctrl(d, (struct sockaddr *) &(d->ctrl),
  591.                 sdes, sdesl, TRUE) < 0) {
  592.                 perror("sending Speak Freely SDES control packet");
  593.         }
  594.         sdes[0] = pid;
  595.     }
  596.     }
  597.  
  598.     ularm(TimerStep);
  599.     signal(SIGALRM, timertick);       /* Reset signal to handle timeout */
  600. }
  601.  
  602. /*  SENDPKT  --  Send a message to all active destinations.  */
  603.  
  604. static int sendpkt(sb)
  605.   struct soundbuf *sb;
  606. {
  607.     struct destination *d;
  608.     int pktlen;
  609.  
  610.     if (gsmcompress && !toasted) {
  611.     gsmcomp(sb);
  612.     }
  613.  
  614.     if (adpcmcompress && !toasted) {
  615.     adpcmcomp(sb);
  616.     }
  617.  
  618.     if (lpccompress && !toasted) {
  619.     lpccomp(sb);
  620.     }
  621.  
  622.     if (lpc10compress && !toasted) {
  623.     lpc10comp(sb);
  624.     }
  625.  
  626.     if (hasFace) {
  627.     sb->compression |= fFaceOffer;
  628.     }
  629.  
  630.     pktlen = sb->buffer.buffer_len + (sizeof(struct soundbuf) - BUFL);
  631.  
  632.     if (vat) {
  633.     pktlen = vatout(sb, 0L, timestamp, spurt);
  634.     timestamp += sound_packet;
  635.     }
  636.  
  637.     if (rtp) {
  638.     pktlen = rtpout(sb, ssrc, timestamp, seq, spurt);
  639.     seq++;
  640.     timestamp += sound_packet;
  641.     }
  642.  
  643.     spurt = FALSE;              /* Not the start of a talk spurt */
  644.  
  645.     for (d = dests; d != NULL; d = d->dnext) {
  646. #ifdef MULTICAST
  647.     if (IN_MULTICAST(d->name.sin_addr.s_addr)) {
  648.         setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL,
  649.         (char *) &(d->time_to_live), sizeof d->time_to_live);
  650.         if (debugging) {
  651.                 fprintf(stderr, "Multicasting with scope of %d to %s.\n",
  652.             d->time_to_live, inet_ntoa(d->name.sin_addr));
  653.         }
  654.     }
  655. #endif
  656.  
  657. #ifdef CRYPTO
  658.     if (d->deskey[0] || d->ideakey[0] || d->blowfish_spec ||
  659.         d->pgpkey[0] || d->otp != NULL) {
  660.         soundbuf ebuf;
  661.         int i;
  662.         LONG slen, plen = 0;
  663.  
  664.         bcopy(sb, &ebuf, pktlen);
  665.         slen = ebuf.buffer.buffer_len;
  666.  
  667.         /* DES encryption. */
  668.  
  669.         if (d->deskey[0]) {
  670.         if (rtp || vat) {
  671.             int vlen = pktlen;
  672.             des_cblock key;
  673.             des_key_schedule sched;
  674.             des_cblock ivec;
  675.  
  676.                     /* If we're DES encrypting we must round the size of
  677.                the data to be sent to be a multiple of 8 so that
  678.                the entire DES frame is sent.  If this is an RTP
  679.                packet, we may have to set the Pad bit in the
  680.                header and include a count of pad bytes at the end
  681.                of the packet. */
  682.  
  683.             bzero(ivec, 8);
  684.             pktlen = (pktlen + 7) & (~7);
  685.             if (debugging) {
  686.                         fprintf(stderr, "Encrypting %d VAT/RTP bytes with DES key.\r\n",
  687.                 pktlen);
  688.             }
  689.             if (pktlen > vlen) {
  690.             bzero(((char *) &ebuf) + vlen, pktlen - vlen);
  691.             }
  692.             if (rtp && (pktlen > vlen)) {
  693.             char *p = (char *) &ebuf;
  694.  
  695.             p[0] |= 0x20; /* Set pad bytes present bit */
  696.             p[pktlen - 1] = pktlen - vlen; /* Set pad count at end */
  697.             }
  698.             des_set_key((des_cblock *) ((rtp ? d->rtpdeskey : d->vatdeskey) + 1), sched);
  699.             des_ncbc_encrypt((des_cblock *) &ebuf,
  700.             (des_cblock *) &ebuf, pktlen, sched,
  701.             (des_cblock *) ivec, DES_ENCRYPT);
  702.             if (vat) {
  703.             pktlen = vlen;
  704.             }
  705.         } else {
  706.             setkey(d->deskey + 1);
  707.  
  708.                     /* If we're DES encrypting we must round the size of
  709.                the data to be sent to be a multiple of 8 so that
  710.                the entire DES frame is sent. */
  711.  
  712.             slen = (slen + 7) & (~7);
  713.             pktlen = slen + (sizeof(struct soundbuf) - BUFL);
  714.             if (debugging) {
  715.                         fprintf(stderr, "Encrypting %d bytes with DES key.\r\n",
  716.                 slen);
  717.             }
  718.             for (i = 0; i < slen; i += 8) {
  719.  
  720.             /* Apply cipher block chaining within the packet. */
  721.  
  722.             if (i > 0) {
  723.                 int j;
  724.  
  725.                 for (j = 0; j < 8; j++) {
  726.                 ebuf.buffer.buffer_val[(i + j)] ^=
  727.                     ebuf.buffer.buffer_val[(i + j) - 8];
  728.                 }
  729.             }
  730.             endes(ebuf.buffer.buffer_val + i);
  731.             }
  732.             ebuf.compression |= fEncDES;
  733.         }
  734.         }
  735.  
  736.         /* IDEA encryption. */
  737.  
  738.         if (d->ideakey[0]) {
  739.         unsigned short iv[4];
  740.  
  741.         bzero(iv, sizeof(iv));
  742.         initcfb_idea(iv, d->ideakey + 1, FALSE);
  743.  
  744.                 /* If we're IDEA encrypting we must round the size of
  745.            the data to be sent to be a multiple of 8 so that
  746.            the entire IDEA frame is sent. */
  747.  
  748.         slen = (slen + 7) & (~7);
  749.         pktlen = slen + (sizeof(struct soundbuf) - BUFL);
  750.         if (debugging) {
  751.                     fprintf(stderr, "Encrypting %d bytes with IDEA key.\r\n",
  752.                 slen);
  753.         }
  754.         ideacfb(ebuf.buffer.buffer_val, slen);
  755.         close_idea();
  756.         ebuf.compression |= fEncIDEA;
  757.         }
  758.  
  759.         /* Blowfish encryption. */
  760.  
  761.         if (d->blowfish_spec) {
  762.         unsigned char iv[8];
  763.  
  764.         bzero(iv, sizeof(iv));
  765.  
  766.                 /* If we're Blowfish encrypting we must round the size of
  767.            the data to be sent to be a multiple of 8 so that
  768.            the entire Blowfish frame is sent. */
  769.  
  770.         slen = (slen + 7) & (~7);
  771.         pktlen = slen + (sizeof(struct soundbuf) - BUFL);
  772.         if (debugging) {
  773.                     fprintf(stderr, "Encrypting %d bytes with Blowfish key.\r\n",
  774.                 slen);
  775.         }
  776.         BF_cbc_encrypt((unsigned char *) ebuf.buffer.buffer_val,
  777.                    (unsigned char *) ebuf.buffer.buffer_val,
  778.                    slen, &(d->blowfishkey), iv, BF_ENCRYPT);
  779.         ebuf.compression |= fEncBF;
  780.         }
  781.  
  782.         /* PGP encryption. */
  783.  
  784.         if (d->pgpkey[0]) {
  785.         unsigned short iv[4];
  786.  
  787.         bzero(iv, sizeof(iv));
  788.         initcfb_idea(iv, d->pgpkey + 1, FALSE);
  789.  
  790.                 /* If we're PGP IDEA encrypting we must round the size of
  791.            the data to be sent to be a multiple of 8 so that
  792.            the entire IDEA frame is sent. */
  793.  
  794.         slen = (slen + 7) & (~7);
  795.         pktlen = slen + (sizeof(struct soundbuf) - BUFL);
  796.         if (debugging) {
  797.                     fprintf(stderr, "Encrypting %d bytes with PGP key.\r\n",
  798.                 slen);
  799.         }
  800.         ideacfb(ebuf.buffer.buffer_val, slen);
  801.         close_idea();
  802.         ebuf.compression |= fEncPGP;
  803.         }
  804.  
  805.         /* Key file encryption. */
  806.  
  807.         if (d->otp != NULL) {
  808.         if (debugging) {
  809.                     fprintf(stderr, "Encrypting %d bytes with key file.\r\n",
  810.                 slen);
  811.         }
  812.         for (i = 0; i < slen; i ++) {
  813.             ebuf.buffer.buffer_val[i] ^= d->otp[i];
  814.         }
  815.         ebuf.compression |= fEncOTP;
  816.         }
  817.  
  818.         if (!rtp && !vat) {
  819.         if (lpc10compress && !toasted) {
  820.             pktlen = lpc10stuff(&ebuf, pktlen);
  821.             if (robust > 1) {
  822.             ebuf.compression |= fCompRobust;
  823.             roSeq(&ebuf) = rseq;
  824.             rseq = (rseq + 1) & 0xFF;
  825.             }
  826.         }
  827.         ebuf.compression = htonl(ebuf.compression);
  828.         ebuf.buffer.buffer_len = htonl(ebuf.buffer.buffer_len);
  829.         }
  830.         for (i = 0; i < (lpc10compress ? robust : 1); i++) {
  831.         if (sendto(sock, (char *) &ebuf, pktlen,
  832.             0, (struct sockaddr *) &(d->name), sizeof d->name) < 0) {
  833.                     perror("sending encrypted audio");
  834.             return FALSE;
  835.         }
  836.         }
  837.     } else
  838. #endif
  839.     {
  840.         int i, wasf = FALSE;
  841.  
  842.         if (!vat && !rtp) {
  843.         wasf = TRUE;
  844.         if (lpc10compress && !toasted) {
  845.             pktlen = lpc10stuff(sb, pktlen);
  846.             if (robust > 1) {
  847.             sb->compression |= fCompRobust;
  848.             sb->buffer.buffer_len |= ((long) rseq) << 24;
  849.             rseq = (rseq + 1) & 0xFF;
  850.             }
  851.         }
  852.         sb->compression = htonl(sb->compression);
  853.         sb->buffer.buffer_len = htonl(sb->buffer.buffer_len);
  854.         }
  855.  
  856.         for (i = 0; i < (lpc10compress ? robust : 1); i++) {
  857.         if (sendto(sock, (char *) sb, pktlen,
  858.             0, (struct sockaddr *) &(d->name), sizeof d->name) < 0) {
  859.                     perror("sending audio");
  860.             return FALSE;
  861.         }
  862.         }
  863.         if (wasf) {
  864.         sb->compression = ntohl(sb->compression);
  865.         sb->buffer.buffer_len = ntohl(sb->buffer.buffer_len);
  866.         if (sb->compression & fCompRobust) {
  867.             sb->compression &= ~fCompRobust;
  868.             sb->buffer.buffer_len &= 0xFFFFFFL;
  869.         }
  870.         if ((sb->compression & fCompLPC10) &&
  871.             (sb->buffer.buffer_len > 16)) {
  872.             pktlen += sizeof(sb->sendinghost);
  873.         }
  874.         }
  875.     }
  876.     }
  877.     return TRUE;
  878. }
  879.  
  880. /*  GETAUDIO  --  Open audio input.  If audio hardware is half duplex,
  881.           we may have to mute output in progress.  */
  882.  
  883. static int getaudio()
  884. {
  885.     int i;
  886.  
  887. #ifdef HALF_DUPLEX
  888.     struct soundbuf hdreq;
  889.     struct sockaddr_in name;
  890.  
  891.     /* If we're afflicted with half-duplex hardware, make several
  892.        attempts to mute the output device and open audio input.
  893.        We send a mute even if the output isn't active as a courtesy
  894.        to the output program; if a later attempt to acquire output
  895.        fails, he'll know it was a result of being muted. */
  896.  
  897.     for (i = 5; i > 0; i--) {
  898.     hdreq.compression = htonl(fProtocol | fHalfDuplex | fHalfDuplexMute);
  899.     strcpy(hdreq.sendinghost, hostname);
  900.     hdreq.buffer.buffer_len = 0;
  901.  
  902.     bcopy((char *) &localhost, (char *) &(name.sin_addr), sizeof localhost);
  903.     name.sin_family = AF_INET;
  904.     name.sin_port = htons(Internet_Port);
  905.     if (debugging) {
  906.             fprintf(stderr,"Sending fHalfDuplex | fHalfDuplexMute Request\n");
  907.     }
  908.     if (sendto(sock, &hdreq, (sizeof(struct soundbuf) - BUFL),
  909.            0, (struct sockaddr *) &name, sizeof name) < 0) {
  910.             perror("sending half-duplex mute request");
  911.     }
  912.     sf_usleep(50000L);
  913.     if (soundinit(O_RDONLY)) {
  914.         halfDuplexMuted = TRUE;
  915.         break;
  916.     }
  917.     }
  918.  
  919.     /* If we failed to initialise, send a resume just in case
  920.        one of our mute requests made it through anyway. */
  921.  
  922.     if (i <= 0) {
  923.     hdreq.compression = htonl(fProtocol | fHalfDuplex | fHalfDuplexResume);
  924.     if (sendto(sock, &hdreq, (sizeof(struct soundbuf) - BUFL),
  925.            0, (struct sockaddr *) &name, sizeof name) < 0) {
  926.             perror("sending half-duplex resume request");
  927.     }
  928.     }
  929. #else
  930.     i = soundinit(O_RDONLY);
  931. #endif
  932.  
  933.     if (i <= 0) {
  934.         fprintf(stderr, "%s: unable to initialise audio.\n", progname);
  935.     return FALSE;
  936.     }
  937.     havesound = TRUE;
  938.     if (agc) {
  939.     soundrecgain(rgain);      /* Set initial record level */
  940.     }
  941.     return TRUE;
  942. }
  943.  
  944. /*  FREEAUDIO  --  Release sound input device, sending a resume to
  945.                    the output device if we've muted it due to
  946.            half-duplex hardware.  */
  947.  
  948. static void freeaudio()
  949. {
  950.     if (havesound) {
  951.     if (debugging) {
  952.             fprintf(stderr, "Restoring audio modes at release.\n");
  953.     }
  954.     soundterm();
  955.     havesound = FALSE;
  956.     }
  957.  
  958. #ifdef HALF_DUPLEX
  959.  
  960.     /* When bailing out, make sure we don't leave the output
  961.        muted. */
  962.  
  963.     if (halfDuplexMuted) {
  964.     struct soundbuf hdreq;
  965.     struct sockaddr_in name;
  966.  
  967.     hdreq.compression = htonl(fProtocol | fHalfDuplex | fHalfDuplexResume);
  968.     strcpy(hdreq.sendinghost, hostname);
  969.     hdreq.buffer.buffer_len = 0;
  970.  
  971.     bcopy((char *) &localhost, (char *) &(name.sin_addr), sizeof localhost);
  972.     name.sin_family = AF_INET;
  973.     name.sin_port = htons(Internet_Port);
  974.     if (sendto(sock, &hdreq, (sizeof(struct soundbuf) - BUFL),
  975.            0, (struct sockaddr *) &name, sizeof name) < 0) {
  976.             perror("sending half-duplex resume request");
  977.     }
  978.     halfDuplexMuted = FALSE;
  979.     }
  980. #endif
  981. }
  982.  
  983. /*  EXITING  --  Catch as many program termination signals as
  984.          possible and restore initial audio modes before
  985.          we exit.  */
  986.  
  987. static void exiting()
  988. {
  989.     struct destination *d;
  990.  
  991.     freeaudio();
  992.  
  993.     if (audioDumpFile != NULL) {
  994.     fclose(audioDumpFile);
  995.     }
  996.  
  997. #ifdef PUSH_TO_TALK
  998.     if (rawmode) {
  999.         fprintf(stderr, "\r      \r");
  1000. #ifdef USE_CURSES
  1001.     nocbreak();
  1002.     echo();
  1003.     endwin();
  1004.     fcntl(fileno(stdin), F_SETFL, 0);
  1005. #else
  1006.     tty_normode();
  1007.     fcntl(fileno(stdin), F_SETFL, 0);
  1008. #endif
  1009.     }
  1010. #endif
  1011.  
  1012.     if (rtp) {
  1013.     for (d = dests; d != NULL; d = d->dnext) {
  1014.         char v[1024];
  1015.         int l;
  1016.  
  1017.             l = rtp_make_bye(v, ssrc, "Exiting Speak Freely", TRUE);
  1018.         if (sendrtpctrl(d, (struct sockaddr *) &(d->ctrl),
  1019.              v, l, TRUE) < 0) {
  1020.                 perror("sending RTCP BYE packet");
  1021.         }
  1022.     }
  1023.     } else if (vat) {
  1024.     for (d = dests; d != NULL; d = d->dnext) {
  1025.         char v[16];
  1026.         int l;
  1027.  
  1028.         l = makevatdone(v, 0L);
  1029.         if (sendrtpctrl(d, (struct sockaddr *) &(d->ctrl),
  1030.              v, l, FALSE) < 0) {
  1031.                 perror("sending VAT DONE control packet");
  1032.         }
  1033.     }
  1034.     } else {
  1035.     for (d = dests; d != NULL; d = d->dnext) {
  1036.         char v[1024];
  1037.         int l;
  1038.  
  1039.             l = rtp_make_bye(v, ssrc, "Exiting Speak Freely", TRUE);
  1040.         v[0] = (v[0] & 0x3F) | (1 << 6);
  1041.         if (sendrtpctrl(d, (struct sockaddr *) &(d->ctrl),
  1042.              v, l, TRUE) < 0) {
  1043.                 perror("sending Speak Freely BYE packet");
  1044.         }
  1045.     }
  1046.     }
  1047.  
  1048.     exit(0);
  1049. }
  1050.  
  1051. /*  CHANGEMODE    --  Reset state when talk/pause/quiet mode changes.  */
  1052.  
  1053. static void changemode()
  1054. {
  1055.     if (talking) {
  1056.     spurt = TRUE;
  1057.     /* Discard all backlog sound input. */
  1058.     soundflush();
  1059.     } else {
  1060.     sqwait = 0;              /* Reset squelch delay */
  1061.     }
  1062. }
  1063.  
  1064. /*  TERMCHAR  --  Check for special characters from console when
  1065.           in raw mode.    */
  1066.  
  1067. static void termchar(ch)
  1068.   int ch;
  1069. {
  1070. #define Ctrl(x) ((x) - '@')
  1071.     if (ch == 'q' || ch == 'Q' || ch == 27 ||
  1072.         ch == Ctrl('C') || ch == Ctrl('D')) {
  1073.     exiting();
  1074.     }
  1075. }
  1076.  
  1077. /*  CHATCHAR  --  Test for text chat request character.  */
  1078.  
  1079. static int chatchar(ch)
  1080.   int ch;
  1081. {
  1082.     if ((!rtp && !vat) && ch == '.') {
  1083.     char s[133];
  1084.  
  1085.     if (rawmode) {
  1086. #ifdef USE_CURSES
  1087.         nocbreak();
  1088.         echo();
  1089.         endwin();
  1090. #else
  1091.         tty_normode();
  1092. #endif
  1093.     }
  1094.     fcntl(fileno(stdin), F_SETFL, 0);
  1095.     if (push) {
  1096.         talking = 0;
  1097.     }
  1098.  
  1099.         fprintf(stderr, "\rChat:  ");
  1100.     while (TRUE) {
  1101.         if (fgets(s, (sizeof s) - 1, stdin) != NULL) {
  1102.         struct destination *d;
  1103.  
  1104.         while (strlen(s) > 0 && isspace(s[strlen(s) - 1])) {
  1105.             s[strlen(s) - 1] = 0;
  1106.         }
  1107.         for (d = dests; d != NULL; d = d->dnext) {
  1108.             char v[256];
  1109.             int l;
  1110.  
  1111.             l = rtp_make_app(v, ssrc, TRUE, RTCP_APP_TEXT_CHAT, s);
  1112.             /* Set Speak Freely protocol flag in packet */
  1113.             v[0] = (v[0] & 0x3F) | (1 << 6);
  1114.             if (sendrtpctrl(d, (struct sockaddr *) &(d->ctrl),
  1115.                  v, l, TRUE) < 0) {
  1116.                         perror("sending text chat packet");
  1117.             }
  1118.         }
  1119. /*
  1120. fprintf(stderr, "\nOut of chat mode, input(%d) = \"%s\"\n", strlen(s), s);
  1121. */
  1122.         fprintf(stderr, talking ? (squelch > 0 ?
  1123.                         "\rQuiet: " : "\rTalk:   ") : "\rPause: ");
  1124.  
  1125.         if (rawmode) {
  1126. #ifdef USE_CURSES
  1127.             initscr();
  1128.             noecho();
  1129.             cbreak();
  1130. #else
  1131.             tty_rawmode();
  1132. #endif
  1133.         }
  1134.         changemode();
  1135.         break;
  1136.         }
  1137.     }
  1138.     fcntl(fileno(stdin), F_SETFL, talking ? O_NDELAY : 0);
  1139.     return TRUE;
  1140.     }
  1141.     return FALSE;
  1142. }
  1143.  
  1144. /*  SENDFILE  --  Send a file or, if the file name is NULL or a
  1145.           single period, send real-time sound input. */
  1146.  
  1147. static int sendfile(f)
  1148.   char *f;
  1149. {
  1150.     soundbuf netbuf;
  1151. #define buf netbuf.buffer.buffer_val
  1152.     int bread, nread, lread;
  1153.     FILE *afile = NULL;
  1154.     static int firstTime = TRUE;
  1155.  
  1156.     if (firstTime) {
  1157.     firstTime = FALSE;
  1158.     signal(SIGHUP, exiting);     /* Set signal to handle termination */
  1159.     signal(SIGINT, exiting);     /* Set signal to handle termination */
  1160.     signal(SIGTERM, exiting);    /* Set signal to handle termination */
  1161.     signal(SIGALRM, timertick);  /* Set signal to handle timer */
  1162.     ularm(TimerStep);
  1163.     }
  1164.  
  1165.     /* Compute the number of sound samples needed to fill a
  1166.        packet of TINY_PACKETS bytes. */
  1167.  
  1168.     if (rtp) {
  1169.     sound_packet = (gsmcompress | lpccompress | adpcmcompress) ? (160 * 4)
  1170.                : 320;
  1171.     } else if (vat) {
  1172.     sound_packet = (gsmcompress | lpccompress | adpcmcompress) ? (160 * 4)
  1173.                : 320;
  1174.     } else {
  1175.     sound_packet = ((TINY_PACKETS - ((sizeof(soundbuf) - BUFL))) *
  1176.             (compressing ? 2 : 1));
  1177.     if (gsmcompress) {
  1178.         sound_packet = compressing ? 3200 : 1600;
  1179.     } else if (adpcmcompress) {
  1180.         sound_packet *= 2;
  1181.         sound_packet -= 4;          /* Leave room for state at the end */
  1182.     } else if (lpccompress) {
  1183.         sound_packet = 10 * LPC_FRAME_SIZE;
  1184.     } else if (lpc10compress) {
  1185.         sound_packet = compressing ? 3600 : 1800;
  1186.     }
  1187.     }
  1188.  
  1189. #ifdef SHOW_PACKET_SIZE
  1190.     printf("Samples per packet = %d\n", sound_packet);
  1191. #endif
  1192.     lread = sound_packet;
  1193.  
  1194.     strcpy(netbuf.sendinghost, hostname);
  1195.     if (f != NULL && (strcmp(f, ".") != 0)) {
  1196.     char magic[4];
  1197.  
  1198.         afile = fopen(f, "r");
  1199.     if (afile == NULL) {
  1200.             fprintf(stderr, "Unable to open sound file %s.\n", f);
  1201.         return 2;
  1202.     }
  1203.  
  1204.     toasted = FALSE;
  1205.         if ((strlen(f) > 4) && (strcmp(f + (strlen(f) - 4), ".gsm") == 0)) {
  1206.         toasted = TRUE;
  1207.         lread = 33 * ((rtp || vat) ? 4 : 10);
  1208.         sound_packet = (160 * lread) / 33;
  1209.     } else {
  1210.  
  1211.         /* If the file has a Sun .au file header, skip it.
  1212.            Note that we still blithely assume the file is
  1213.            8-bit ISDN u-law encoded at 8000 samples per
  1214.            second. */
  1215.  
  1216.         fread(magic, 1, sizeof(long), afile);
  1217.             if (bcmp(magic, ".snd", 4) == 0) {
  1218.         long startpos;
  1219.  
  1220.         fread(&startpos, sizeof(long), 1, afile);
  1221.         fseek(afile, ntohl(startpos), 0);
  1222.         } else {
  1223.         fseek(afile, 0L, 0);
  1224.         }
  1225.     }
  1226.     }
  1227.  
  1228.     /* Send a file */
  1229.  
  1230.     if (afile) {
  1231.     int tlast = FALSE;
  1232. #ifdef BSD_like
  1233.     struct timeb t1, t2, tl;
  1234. #else
  1235.     struct timeval t1, t2, tl;
  1236. #endif
  1237.     long et, corr = 0;
  1238.  
  1239.     while (
  1240. #ifdef BSD_like
  1241.         ftime(&t1),
  1242. #else
  1243.         gettimeofday(&t1, NULL),
  1244. #endif
  1245.  
  1246.         (bread = nread =
  1247.         fread(buf + (toasted ? 2 : 0), 1,
  1248.                   lread,
  1249.                   afile)) > 0) {
  1250.         netbuf.compression = fProtocol | (ring ? (fSetDest | fDestSpkr) : 0);
  1251.         ring = FALSE;
  1252.         netbuf.compression |= debugging ? fDebug : 0;
  1253.         netbuf.compression |= loopback ? fLoopBack : 0;
  1254.         if (toasted) {
  1255.         *((short *) netbuf.buffer.buffer_val) = bread = (160 * nread) / 33;
  1256.         netbuf.buffer.buffer_len = lread + sizeof(short);
  1257.         netbuf.compression |= fCompGSM;
  1258.         } else {
  1259.         if (compressing) {
  1260.             int is = nread, os = nread / 2;
  1261.  
  1262.             rate_flow(buf, buf, &is, &os);
  1263.             nread = os;
  1264.             netbuf.compression |= fComp2X;
  1265.         }
  1266.         netbuf.buffer.buffer_len = nread;
  1267.         }
  1268.         if (!sendpkt(&netbuf)) {
  1269.         fclose(afile);
  1270.         toasted = FALSE;
  1271.         exiting();
  1272.         }
  1273.  
  1274.             /* The following code is needed because when we're reading
  1275.            sound from a file, as opposed to receiving it in real
  1276.            time from the CODEC, we must meter out the samples
  1277.            at the rate they will actually be played by the destination
  1278.            machine.  For a 8000 samples per second, this amounts
  1279.            to 125 microseconds per sample, minus the time we spent
  1280.            compressing the data (which is substantial for GSM) and
  1281.            encrypting the data.
  1282.  
  1283.                What we're trying to accomplish here is to maintain a
  1284.            predictable time between packets equal to the sample
  1285.            rate.  This is, of course, very difficult since system
  1286.            performance and instantaneous load changes the relationship
  1287.            between the compute time per packet and the length of
  1288.            the sound it represents.  What the code below does is
  1289.            measure the actual time between packets, compare it to
  1290.            the desired time, then use the error signal as input
  1291.            to an exponentially smoothed moving average with P=0.1
  1292.            which adjusts the time, in microseconds, we wait between
  1293.            packets.  This quickly adapts to the correct wait time
  1294.            based on system performance and options selected, while
  1295.            minimsing perturbations due to momentary changes in
  1296.            system load.  Due to incompatibilities between System V
  1297.            and BSD-style gettimeofday(), we do this differently
  1298.            for the two styles of system.  If the system conforms
  1299.            to neither convention, we just guess based on the number
  1300.            of samples in the packet and a fudge factor. */
  1301.  
  1302. #define kOverhead   8000
  1303.  
  1304. #ifdef BSD_like
  1305.         ftime(&t2);
  1306.         if (tlast) {
  1307.         long dt =  1000 * (((t2.time - tl.time) * 1000) +
  1308.                    (t2.millitm - tl.millitm)),
  1309.                atime = bread * 125, error;
  1310.         error = atime - dt;
  1311.         if (error > atime / 2) {
  1312.             error = atime / 2;
  1313.         } else if (error < -(atime / 2)) {
  1314.             error = -(atime / 2);
  1315.         }
  1316.         corr = corr - 0.1 * error;
  1317.         et = atime - corr;
  1318. #ifdef DEBUG_SOUNDFILE_WAIT
  1319. printf("Packet time %d Delta t = %d Error = %d, Corr = %d, Wait = %d\n",
  1320.     atime, dt, error, corr, et);
  1321. #endif
  1322.         } else {
  1323. #ifdef __FreeBSD__
  1324.         corr = 80000;
  1325. #else
  1326.         corr = 8000;
  1327. #endif
  1328.         et = ((bread * 125) -
  1329.               1000 * (((t2.time - t1.time) * 1000) +
  1330.                    (t2.millitm - t1.millitm))) - kOverhead;
  1331.         }
  1332.         tl = t2;
  1333.         tlast = TRUE;
  1334. #else
  1335.         gettimeofday(&t2, NULL);
  1336.         if (tlast) {
  1337.         long dt = (t2.tv_sec - tl.tv_sec) * 1000000 +
  1338.                 (t2.tv_usec - tl.tv_usec),
  1339.              atime = bread * 125, error;
  1340.         error = atime - dt;
  1341.         if (error > atime / 2) {
  1342.             error = atime / 2;
  1343.         } else if (error < -(atime / 2)) {
  1344.             error = -(atime / 2);
  1345.         }
  1346.         corr = corr - 0.1 * error;
  1347.         et = atime - corr;
  1348. #ifdef DEBUG_SOUNDFILE_WAIT
  1349. printf("Packet time %d Delta t = %d Error = %d, Corr = %d, Wait = %d\n",
  1350.     atime, dt, error, corr, et);
  1351. #endif
  1352.         } else {
  1353.         et = ((bread * 125) -
  1354.                   (t2.tv_sec - t1.tv_sec) * 1000000 +
  1355.                   (t2.tv_usec - t1.tv_usec)) - kOverhead;
  1356.         }
  1357.         tl = t2;
  1358.         tlast = TRUE;
  1359. #endif
  1360.  
  1361.         if (et > 0) {
  1362.         sf_usleep(et);
  1363.         }
  1364.         if (debugging && !vat && !rtp) {
  1365.                 fprintf(stderr, "Sent %d samples from %s in %d bytes.\r\n",
  1366.             bread, f, ntohl(netbuf.buffer.buffer_len));
  1367.         }
  1368.     }
  1369.  
  1370.     if (debugging) {
  1371.             fprintf(stderr, "Sent sound file %s.\r\n", f);
  1372.     }
  1373.     fclose(afile);
  1374.     toasted = FALSE;
  1375.     } else {
  1376.  
  1377.         /* Send real-time audio. */
  1378.  
  1379. #ifdef PUSH_TO_TALK
  1380.     if (push) {
  1381.         char c;
  1382.         int l;
  1383.  
  1384.         fprintf(stderr,
  1385.                 "Space bar switches talk/pause, Esc or \"q\" to quit, \".\" for chat text\nPause: ");
  1386.         fflush(stderr);
  1387. #ifdef USE_CURSES
  1388.         initscr();
  1389.         noecho();
  1390.         cbreak();
  1391. #else
  1392.         tty_rawmode();
  1393. #endif
  1394.         rawmode = TRUE;
  1395.         while (TRUE) {
  1396.         while (TRUE) {
  1397.             if (l = read(fileno(stdin), &c, 1) == 1 || errno != EINTR) {
  1398.             break;
  1399.             }
  1400.         }
  1401.         if (l == 1 && !chatchar(c)) {
  1402.             break;
  1403.         }
  1404.         }
  1405.         if (l != 1) {
  1406.                 perror("waiting for first Pause/Talk character");
  1407.         }
  1408.         termchar(c);
  1409.             fprintf(stderr, squelch > 0 ? "\rQuiet:  " : "\rTalk:   ");
  1410.         fcntl(fileno(stdin), F_SETFL, O_NDELAY);
  1411.         talking = TRUE;
  1412.         spurt = TRUE;
  1413.     }
  1414. #endif
  1415.  
  1416.     /* Send real-time sound. */
  1417.  
  1418. #ifdef Solaris
  1419.     setaubufsize(sound_packet);
  1420. #endif
  1421.  
  1422.     if (!getaudio()) {
  1423.             fprintf(stderr, "Unable to initialise audio.\n");
  1424.         return 2;
  1425.     }
  1426.     changemode();
  1427.     while (TRUE) {
  1428.         int soundel = 0;
  1429.         unsigned char *bs = (unsigned char *) buf;
  1430.  
  1431.         if (havesound) {
  1432.  
  1433.                 /* Obtain a packet's worth of real-time audio from
  1434.            the audio input hardware. */
  1435.  
  1436.         soundel = soundgrab(buf, sound_packet);
  1437.  
  1438.         /* If a raw audio dump file (-w option) is specified,
  1439.            dump whatever we got from the audio input to the
  1440.            designated file.  This can come in handy when
  1441.                    debugging audio drivers which don't provide samples
  1442.            in the expected 8 bit mu-law mode. */
  1443.  
  1444.         if ((audioDumpFile != NULL) && (soundel > 0)) {
  1445.             fwrite(buf, 1, soundel, audioDumpFile);
  1446.         }
  1447.         }
  1448.  
  1449. #ifdef PUSH_TO_TALK
  1450.         while (push) {
  1451.         char c;
  1452.         int rlen;
  1453.  
  1454.         if ((rlen = read(fileno(stdin), &c, 1)) > 0
  1455. #ifdef HEWLETT_PACKARD
  1456.             || HPTermHookChar
  1457. #endif
  1458.            ) {
  1459. #ifdef HEWLETT_PACKARD
  1460.             c = HPTermHookChar;
  1461. #endif
  1462.             if (rlen > 0 && chatchar(c)) {
  1463.             continue;
  1464.             }
  1465.             termchar(c);
  1466.             talking = !talking;
  1467.             fflush(stderr);
  1468. #ifdef HALF_DUPLEX
  1469.  
  1470.             /* For half-duplex, acquire and release the
  1471.                audio device at each transition.  This lets
  1472.                us mute the output only while in Talk mode. */
  1473.  
  1474.             if (talking) {
  1475.             if (!getaudio()) {
  1476.                             fprintf(stderr, "Audio device busy.\n");
  1477.                 talking = FALSE;
  1478.             }
  1479.             } else {
  1480.             freeaudio();
  1481.             }
  1482. #endif
  1483.             fprintf(stderr, talking ? (squelch > 0 ?
  1484.                             "\rQuiet: " : "\rTalk:   ") : "\rPause: ");
  1485.             fcntl(fileno(stdin), F_SETFL, talking ? O_NDELAY : 0);
  1486. #ifdef OBSOLETE
  1487.             if (talking) {
  1488.             spurt = TRUE;
  1489.             /* Discard all backlog sound input. */
  1490.             soundflush();
  1491. fprintf(stderr, "\n**flush**\n");
  1492.             } else {
  1493.             sqwait = 0;   /* Reset squelch delay */
  1494.             }
  1495. #endif
  1496.             changemode();
  1497.             break;
  1498.         } else {
  1499.             if (rlen == -1 && errno == EINTR) {
  1500.             continue;
  1501.             }
  1502.             break;
  1503.         }
  1504.         }
  1505. #endif
  1506.  
  1507.         if (soundel > 0) {
  1508.         register unsigned char *start = bs;
  1509.         register int j;
  1510.         int squelched = (squelch > 0), osl = soundel;
  1511.  
  1512.         /* If entire buffer is less than squelch, ditch it.  If
  1513.                    we haven't received sqdelay samples since the last
  1514.            squelch event, continue to transmit. */
  1515.  
  1516.         if (sqdelay > 0 && sqwait > 0) {
  1517.             if (debugging) {
  1518.                         printf("Squelch countdown: %d samples left.\n",
  1519.                 sqwait);
  1520.             }
  1521.             sqwait -= soundel;
  1522.             squelched = FALSE;
  1523. #ifdef PUSH_TO_TALK
  1524.             if (sqwait <= 0 && push) {
  1525.                         fprintf(stderr, "\rQuiet: ");
  1526.             }
  1527. #endif
  1528.         } else if (squelch > 0) {
  1529.             for (j = 0; j < soundel; j++) {
  1530. #ifdef USQUELCH
  1531.             if (((*start++ & 0x7F) ^ 0x7F) > squelch)
  1532. #else
  1533.             int samp = audio_u2s(*start++);
  1534.  
  1535.             if (samp < 0) {
  1536.                 samp = -samp;
  1537.             }
  1538.             if (samp > squelch)
  1539. #endif
  1540.             {
  1541.                 squelched = FALSE;
  1542. #ifdef PUSH_TO_TALK
  1543.                 if (sqwait <= 0 && push) {
  1544.                                fprintf(stderr, "\rTalk:  ");
  1545.                 }
  1546. #endif
  1547.                 sqwait = sqdelay;
  1548.                 break;
  1549.             }
  1550.             }
  1551.         }
  1552.  
  1553.         if (squelched) {
  1554.             if (debugging) {
  1555.                         printf("Entire buffer squelched.\n");
  1556.             }
  1557.             spurt = TRUE;
  1558.         } else {
  1559.             netbuf.compression = fProtocol | (ring ? (fSetDest | fDestSpkr) : 0);
  1560.             netbuf.compression |= debugging ? fDebug : 0;
  1561.             netbuf.compression |= loopback ? fLoopBack : 0;
  1562.  
  1563.             /* If automatic gain control is enabled,
  1564.                ride the gain pot to fill the dynamic range
  1565.                optimally. */
  1566.  
  1567.             if (agc) {
  1568.             register unsigned char *start = bs;
  1569.             register int j;
  1570.             long msamp = 0;
  1571.  
  1572.             for (j = 0; j < soundel; j++) {
  1573.                 int s = audio_u2s(*start++);
  1574.  
  1575.                 msamp += (s < 0) ? -s : s;
  1576.             }
  1577.             msamp /= soundel;
  1578.             if (msamp < 6000) {
  1579.                 if (rgain < 100) {
  1580.                 soundrecgain(++rgain);
  1581.                 }
  1582.             } else if (msamp > 7000) {
  1583.                 if (rgain > 1) {
  1584.                 soundrecgain(--rgain);
  1585.                 }
  1586.             }
  1587.             }
  1588.  
  1589.             ring = FALSE;
  1590.             if (compressing) {
  1591.             int is = soundel, os = soundel / 2;
  1592.  
  1593.             rate_flow(buf, buf, &is, &os);
  1594.             soundel = os;
  1595.             netbuf.compression |= fComp2X;
  1596.             }
  1597.             netbuf.buffer.buffer_len = soundel;
  1598.             if (!sendpkt(&netbuf)) {
  1599.             exiting();
  1600.             }
  1601.             if (debugging && !vat && !rtp) {
  1602.                         fprintf(stderr, "Sent %d audio samples in %d bytes.\r\n",
  1603.                 osl, soundel);
  1604.             }
  1605.         }
  1606.         } else {
  1607.         sf_usleep(100000L);  /* Wait for some sound to arrive */
  1608.         }
  1609.     }
  1610.     }
  1611.     return 0;
  1612. }
  1613.  
  1614. /*  MAKESESSIONKEY  --    Generate session key with optional start
  1615.             key.  If mode is TRUE, the key will be
  1616.             translated to a string, otherwise it is
  1617.             returned as 16 binary bytes.  */
  1618.  
  1619. static void makeSessionKey(key, seed, mode)
  1620.   char *key, *seed;
  1621.   int mode;
  1622. {
  1623.     int j, k;
  1624.     struct MD5Context md5c;
  1625.     char md5key[16], md5key1[16];
  1626.     char s[1024];
  1627.  
  1628.     s[0] = 0;
  1629.     if (seed != NULL) {
  1630.     strcat(s, seed);
  1631.     }
  1632.  
  1633.     /* The following creates a seed for the session key generator
  1634.        based on a collection of volatile and environment-specific
  1635.        information unlikely to be vulnerable (as a whole) to an
  1636.        exhaustive search attack.  If one of these items isn't
  1637.        available on your machine, replace it with something
  1638.        equivalent or, if you like, just delete it. */
  1639.  
  1640.     sprintf(s + strlen(s), "%u", getpid());
  1641.     sprintf(s + strlen(s), "%u", getppid());
  1642.     V getcwd(s + strlen(s), 256);
  1643.     sprintf(s + strlen(s), "%u", clock());
  1644.     V cuserid(s + strlen(s));
  1645.     sprintf(s + strlen(s), "%u", time(NULL));
  1646. #ifdef Solaris
  1647.     sysinfo(SI_HW_SERIAL,s + strlen(s), 12);
  1648. #else
  1649.     sprintf(s + strlen(s), "%u", gethostid());
  1650. #endif
  1651.     getdomainname(s + strlen(s), 256);
  1652.     gethostname(s + strlen(s), 256);
  1653.     sprintf(s + strlen(s), "%u", getuid());
  1654.     sprintf(s + strlen(s), "%u", getgid());
  1655.     MD5Init(&md5c);
  1656.     MD5Update(&md5c, s, strlen(s));
  1657.     MD5Final(md5key, &md5c);
  1658.     sprintf(s + strlen(s), "%u", (time(NULL) + 65121) ^ 0x375F);
  1659.     MD5Init(&md5c);
  1660.     MD5Update(&md5c, s, strlen(s));
  1661.     MD5Final(md5key1, &md5c);
  1662. #ifdef CRYPTO
  1663.     init_idearand(md5key, md5key1, time(NULL));
  1664. #define nextrand    idearand()
  1665. #else
  1666. #define nextrand    (md5key[j] ^ md5key1[j])
  1667. #endif
  1668.     if (mode) {
  1669.     for (j = k = 0; j < 16; j++) {
  1670.         unsigned char rb = nextrand;
  1671.  
  1672. #define Rad16(x) ((x) + 'A')
  1673.         key[k++] = Rad16((rb >> 4) & 0xF);
  1674.         key[k++] = Rad16(rb & 0xF);
  1675. #undef Rad16
  1676.         if (j & 1) {
  1677.                 key[k++] = '-';
  1678.         }
  1679.     }
  1680.     key[--k] = 0;
  1681.     } else {
  1682.     for (j = 0; j < 16; j++) {
  1683.         key[j] = nextrand;
  1684.     }
  1685.     }
  1686. #ifdef CRYPTO
  1687.     close_idearand();
  1688. #endif
  1689. #undef nextrand
  1690. }
  1691.  
  1692. /*  PROG_NAME  --  Extract program name from argv[0].  */
  1693.  
  1694. static char *prog_name(arg)
  1695.   char *arg;
  1696. {
  1697.     char *cp = strrchr(arg, '/');
  1698.  
  1699.     return (cp != NULL) ? cp + 1 : arg;
  1700. }
  1701.  
  1702. /*  USAGE  --  Print how-to-call information.  */
  1703.  
  1704. static void usage()
  1705. {
  1706.     V fprintf(stderr, "%s  --  Speak Freely sound sender.\n", progname);
  1707.     V fprintf(stderr, "            %s.\n", Relno);
  1708.     V fprintf(stderr, "\n");
  1709.     V fprintf(stderr, "Usage: %s hostname[:port] [options] [ file1 / . ]...\n", progname);
  1710.     V fprintf(stderr, "Options: (* indicates defaults)\n");
  1711. #ifdef PUSH_TO_TALK
  1712.     V fprintf(stderr, "           -A         Always transmit unless squelched\n");
  1713.     V fprintf(stderr, "     *     -B         Push to talk using keyboard\n");
  1714. #endif
  1715. #ifdef CRYPTO
  1716.     V fprintf(stderr, "           -BFkey     Blowfish encrypt with key\n");
  1717. #endif
  1718.     V fprintf(stderr, "           -C         Compress subsequent sound\n");
  1719.     V fprintf(stderr, "           -D         Enable debug output\n");
  1720. #ifdef CRYPTO
  1721.     V fprintf(stderr, "           -E[key]    Emit session key string\n");
  1722. #endif
  1723.     V fprintf(stderr, "           -F         ADPCM compression\n");
  1724.     V fprintf(stderr, "           -G         Automatic gain control\n");
  1725. #ifdef CRYPTO
  1726.     V fprintf(stderr, "           -Ikey      IDEA encrypt with key\n");
  1727.     V fprintf(stderr, "           -Kkey      DES encrypt with key\n");
  1728. #endif
  1729.     V fprintf(stderr, "           -L         Remote loopback\n");
  1730.     V fprintf(stderr, "           -LPC       LPC compression\n");
  1731.     V fprintf(stderr, "           -LPC10Rn   LPC-10 compression, n copies\n");
  1732.     V fprintf(stderr, "     *     -M         Manual record gain control\n");
  1733.     V fprintf(stderr, "           -N         Do not compress subsequent sound\n");
  1734. #ifdef CRYPTO
  1735.     V fprintf(stderr, "           -Ofile     Use file as key file\n");
  1736. #endif
  1737.     V fprintf(stderr, "           -Phostname[:port] Party line, add host to list\n");
  1738.     V fprintf(stderr, "     *     -Q         Disable debug output\n");
  1739.     V fprintf(stderr, "           -R         Ring--force volume, output to speaker\n");
  1740.     V fprintf(stderr, "           -RTP       Use Internet Real-Time Protocol\n");
  1741.     V fprintf(stderr, "           -Sn,t      Squelch at level n (0-32767), timeout t milliseconds\n");
  1742.  
  1743.     V fprintf(stderr, "     *     -T         Telephone (GSM) compression\n");
  1744. #ifdef OBSOLETE
  1745.     V fprintf(stderr, "           -TC        GSM with corrected x86 byte order\n");
  1746. #endif
  1747. #ifdef BYTE_SWAP_DEBUG
  1748.     V fprintf(stderr, "           -TD        Debug: send GSM with swapped byte order\n");
  1749. #endif
  1750.     V fprintf(stderr, "           -U         Print this message\n");
  1751.     V fprintf(stderr, "           -VAT       Use VAT protocol\n");
  1752.     V fprintf(stderr, "           -Wfile     Write raw audio input to file\n");
  1753. #ifdef AUDIO_DEVICE_FILE
  1754.     V fprintf(stderr, "           -Yindev[:ctldev] Override default audio device file name or specify open #fd\n");
  1755. #endif
  1756. #ifdef CRYPTO
  1757.     V fprintf(stderr, "           -Z\"user..\" Send PGP session key for user(s)\n");
  1758. #endif
  1759.     V fprintf(stderr, "\n");
  1760.     V fprintf(stderr, "by John Walker\n");
  1761.     V fprintf(stderr, "   http://www.fourmilab.ch/\n");
  1762. #ifndef CRYPTO
  1763.     V fprintf(stderr, "\n");
  1764.     V fprintf(stderr, "Note: This version of Speak Freely was built with\n");
  1765.     V fprintf(stderr, "      encryption code removed to permit redistribution\n");
  1766.     V fprintf(stderr, "      without concern for export control and regulations\n");
  1767.     V fprintf(stderr, "      concerning encryption technology in some jurisdictions.\n");
  1768.     V fprintf(stderr, "      You can download a version of Speak Freely with\n");
  1769.     V fprintf(stderr, "      full encryption from:\n");
  1770.     V fprintf(stderr, "             http://www.fourmilab.ch/speakfree/unix/\n");
  1771. #endif
  1772. }
  1773.  
  1774. /*  Main program.  */
  1775.  
  1776. main(argc, argv)
  1777.   int argc;
  1778.   char *argv[];
  1779. {
  1780.     int i, j, k, l, sentfile = 0;
  1781.     FILE *fp;
  1782.     struct MD5Context md5c;
  1783.     static lpcstate_t lpcc;
  1784.     char md5key[16], md5key1[16];
  1785.     char s[1024];
  1786.  
  1787.     progname = prog_name(argv[0]);
  1788.     if (gethostname(hostname, sizeof hostname) == -1) {
  1789.         strcpy(hostname, "localhost");
  1790.     } else {
  1791.     if (strlen(hostname) > 15) {
  1792.         hostname[15] = 0;
  1793.     }
  1794.     }
  1795.  
  1796. #ifdef LINUX_FPU_FIX
  1797.     __setfpucw(_FPU_IEEE);          /* Mask floating point interrupts to
  1798.                      enable standard IEEE processing.
  1799.                      Current libc releases do this by
  1800.                      default, so this is needed only on
  1801.                      older libraries. */
  1802. #endif
  1803.     rate_start(8000, 4000);
  1804.     gsmh = gsm_create();
  1805.  
  1806.     /* Initialise LPC decoding. */
  1807.  
  1808.     if (!lpc_start()) {
  1809.         fprintf(stderr, "Cannot allocate LPC decoding memory.\n");
  1810.     return 1;
  1811.     }
  1812.     lpc_init(&lpcc);
  1813.     lpc10init();
  1814.  
  1815. #ifdef sgi
  1816.     usticks = 1000000 / CLK_TCK;
  1817. #endif
  1818.  
  1819. #ifdef HALF_DUPLEX
  1820.     {
  1821. #ifndef INADDR_LOOPBACK
  1822.     /* The standard local host loopback address is supposed to be
  1823.        defined in <netinet/in.h>, but just in case some screwball
  1824.            system doesn't, let's include our own definition here. */
  1825. #define INADDR_LOOPBACK  0x7F000001
  1826. #endif
  1827.     localhost.s_addr = htonl(INADDR_LOOPBACK);
  1828. #ifdef HDX_DEBUG
  1829.         fprintf(stderr, "%s: local host %s\n", progname,
  1830.         inet_ntoa(localhost));
  1831. #endif
  1832.     }
  1833. #endif
  1834.  
  1835.     /* Create the socket used to send data. */
  1836.  
  1837.     sock = socket(AF_INET, SOCK_DGRAM, 0);
  1838.     if (sock < 0) {
  1839.         perror("opening datagram socket");
  1840.     return 1;
  1841.     }
  1842.  
  1843.     /* Initialise randomised packet counters. */
  1844.  
  1845.     makeSessionKey(md5key, NULL, FALSE);
  1846.     bcopy(md5key, (char *) &ssrc, sizeof ssrc);
  1847.     bcopy(md5key + sizeof ssrc, (char *) ×tamp,
  1848.       sizeof timestamp);
  1849.     bcopy(md5key + sizeof ssrc + sizeof timestamp,
  1850.       (char *) &seq, sizeof seq);
  1851.     bcopy(md5key + sizeof ssrc + sizeof timestamp +
  1852.       sizeof seq, &rtpdesrand, sizeof rtpdesrand);
  1853.     sdesl = rtp_make_sdes(&sdes, ssrc, -1, TRUE);
  1854.  
  1855.     /* See if there's a face image file for this user.  If
  1856.        so, we'll offer our face in sound packets we send. */
  1857.  
  1858.     {   char *cp = getenv("SPEAKFREE_FACE");
  1859.     FILE *facefile;
  1860.  
  1861.     if (cp != NULL) {
  1862.             if ((facefile = fopen(cp, "r")) == NULL) {
  1863.                 fprintf(stderr, "%s: cannot open SPEAKFREE_FACE file %s\n",
  1864.             progname, cp);
  1865.         } else {
  1866.         fclose(facefile);
  1867.         hasFace = TRUE;
  1868.         }
  1869.     }
  1870.     }
  1871.  
  1872.     /*    Process command line options.  */
  1873.  
  1874.     for (i = 1; i < argc; i++) {
  1875.     char *op, opt;
  1876.  
  1877.     op = argv[i];
  1878.         if (*op == '-') {
  1879.         opt = *(++op);
  1880.         if (islower(opt)) {
  1881.         opt = toupper(opt);
  1882.         }
  1883.  
  1884.         switch (opt) {
  1885.  
  1886. #ifdef PUSH_TO_TALK
  1887.                 case 'A':             /* -A  --  Always transmit (no push to talk) */
  1888.             push = FALSE;
  1889.             break;
  1890.  
  1891.                 case 'B':             /* -B  -- Push to talk (button) */
  1892. #ifdef CRYPTO
  1893.                       /* -BFkey  -- Set Blowfish key */
  1894.                     if (ucase(op[1]) == 'F') {
  1895.             if (strlen(op + 2) == 0) {
  1896.                 curblowfish_spec = FALSE;
  1897.             } else {
  1898.                 unsigned char bfvec[16];
  1899.  
  1900.                 curblowfish_spec = TRUE;
  1901.                 MD5Init(&md5c);
  1902.                 MD5Update(&md5c, op + 2, strlen(op + 2));
  1903.                 MD5Final(bfvec, &md5c);
  1904.                 BF_set_key(&(curblowfishkey), 16, bfvec);
  1905.                 if (debugging) {
  1906.                                 fprintf(stderr, "Blowfish key:");
  1907.                 for (j = 0; j < 16; j++) {
  1908.                                     fprintf(stderr, " %02X", (bfvec[j] & 0xFF));
  1909.                 }
  1910.                                 fprintf(stderr, "\n");
  1911.                 }
  1912.             }
  1913.             } else {
  1914. #endif
  1915.             if (isatty(fileno(stdin))) {
  1916.                 push = TRUE;
  1917.             }
  1918. #ifdef CRYPTO
  1919.             }
  1920. #endif
  1921.             break;
  1922. #endif
  1923.  
  1924.                 case 'C':             /* -C  -- Compress sound samples */
  1925.             compressing = TRUE;
  1926.             break;
  1927.  
  1928.                 case 'D':             /* -D  --  Enable debug output  */
  1929.             debugging = TRUE;
  1930.             break;
  1931.  
  1932. #ifdef CRYPTO
  1933.                 case 'E':             /* -E  --  Emit session key and exit */
  1934.             makeSessionKey(s, op + 1, TRUE);
  1935.                     printf("%s\n", s);
  1936.             return 0;
  1937. #endif
  1938.  
  1939.                 case 'F':             /* -F -- ADPCM compression */
  1940.             adpcmcompress = TRUE;
  1941.             gsmcompress = lpccompress = lpc10compress = FALSE;
  1942.             break;
  1943.  
  1944.                 case 'G':             /* -G  --  Automatic gain control */
  1945.             agc = TRUE;
  1946.             break;
  1947.  
  1948. #ifdef CRYPTO
  1949.                 case 'I':             /* -Ikey  --  Set IDEA key */
  1950.             if (strlen(op + 1) == 0) {
  1951.             curideakey[0] = FALSE;
  1952.             } else {
  1953.             MD5Init(&md5c);
  1954.             MD5Update(&md5c, op + 1, strlen(op + 1));
  1955.             MD5Final(curideakey + 1, &md5c);
  1956.             curideakey[0] = TRUE;
  1957.             if (debugging) {
  1958.                             fprintf(stderr, "IDEA key:");
  1959.                 for (j = 1; j < 17; j++) {
  1960.                                 fprintf(stderr, " %02X", (curideakey[j] & 0xFF));
  1961.                 }
  1962.                             fprintf(stderr, "\n");
  1963.             }
  1964.             }
  1965.             break;
  1966.  
  1967.                 case 'K':             /* -Kkey  --  Set DES key */
  1968.             desinit(1);       /* Initialise the DES library */
  1969.             if (strlen(op + 1) == 0) {
  1970.             curkey[0] = currtpkey[0] = curvatkey[0] = FALSE;
  1971.             } else {
  1972.             char algorithm[16];
  1973.  
  1974.             MD5Init(&md5c);
  1975.             MD5Update(&md5c, op + 1, strlen(op + 1));
  1976.             MD5Final(md5key, &md5c);
  1977.             for (j = 0; j < 8; j++) {
  1978.                 curkey[j + 1] = (char)
  1979.                       ((md5key[j] ^ md5key[j + 8]) & 0x7F);
  1980.             }
  1981.             if (debugging) {
  1982.                             fprintf(stderr, "DES key:");
  1983.                 for (j = 0; j < 8; j++) {
  1984.                                 fprintf(stderr, " %02X", (curkey[j + 1] & 0xFF));
  1985.                 }
  1986.                             fprintf(stderr, "\n");
  1987.             }
  1988.             curkey[0] = TRUE;
  1989.             des_string_to_key(op + 1, (des_cblock *) (curvatkey + 1));
  1990.             string_DES_key(op + 1, currtpkey + 1, algorithm);
  1991.                         if (strcmp(algorithm, "DES-CBC") != 0) {
  1992.                             fprintf(stderr, "Unsupported encryption algorithm: %s.  Only DES-CBC is available.\n",
  1993.                     algorithm);
  1994.                 return 2;
  1995.             }
  1996.             currtpkey[0] = curvatkey[0] = TRUE;
  1997.             if (debugging) {
  1998.                             fprintf(stderr, "RTP key:");
  1999.                 for (j = 0; j < 8; j++) {
  2000.                                 fprintf(stderr, " %02X", (currtpkey[j + 1] & 0xFF));
  2001.                 }
  2002.                             fprintf(stderr, "\n");
  2003.             }
  2004.             if (debugging) {
  2005.                             fprintf(stderr, "VAT key:");
  2006.                 for (j = 0; j < 8; j++) {
  2007.                                 fprintf(stderr, " %02X", (curvatkey[j + 1] & 0xFF));
  2008.                 }
  2009.                             fprintf(stderr, "\n");
  2010.             }
  2011.             }
  2012.             break;
  2013. #endif
  2014.  
  2015.                 case 'L':             /* -L      --  Remote loopback */
  2016.                       /* -LPC     --  LPC compress sound */
  2017.                       /* -LPC10  --  LPC10 compress sound */
  2018.                     if (ucase(op[1]) == 'P') {
  2019.                         if (strlen(op) > 3 && op[3] == '1') {
  2020.                 lpc10compress = TRUE;
  2021.                 gsmcompress = adpcmcompress = lpccompress = FALSE;
  2022.                 robust = 1;
  2023.                             if (strlen(op) > 5 && ucase(op[5]) == 'R') {
  2024.                 robust = 2;
  2025.                 if (strlen(op) > 6 && isdigit(op[6])) {
  2026.                     robust = atoi(op + 6);
  2027.                     if (robust <= 0) {
  2028.                     robust = 1;
  2029.                     } else if (robust > 4) {
  2030.                     robust = 4;
  2031.                     }
  2032.                 }
  2033.                 }
  2034.             } else {
  2035.                 lpccompress = TRUE;
  2036.                 gsmcompress = adpcmcompress = lpc10compress = FALSE;
  2037.             }
  2038.             } else {
  2039.             loopback = TRUE;
  2040.             }
  2041.             break;
  2042.  
  2043.                 case 'M':             /* -M  --  Manual record gain control */
  2044.             agc = FALSE;
  2045.             break;
  2046.  
  2047.                 case 'N':             /* -N  --  Do not compress sound samples */
  2048.             compressing = FALSE;
  2049.             gsmcompress = FALSE;
  2050.             lpccompress = FALSE;
  2051.             lpc10compress = FALSE;
  2052.             adpcmcompress = FALSE;
  2053.             break;
  2054.  
  2055. #ifdef CRYPTO
  2056.                 case 'O':             /* -Ofile -- Use file as key file */
  2057.             if (op[1] == 0) {
  2058.             curotp = NULL; /* Switch off key file */
  2059.             } else {
  2060.                         fp = fopen(op + 1, "r");
  2061.             if (fp == NULL) {
  2062.                             perror("Cannot open key file");
  2063.                 return 2;
  2064.             }
  2065.             curotp = malloc(BUFL);
  2066.             if (curotp == NULL) {
  2067.                             fprintf(stderr, "Cannot allocate key file buffer.\n");
  2068.                 return 2;
  2069.             }
  2070.             l = fread(curotp, 1, BUFL, fp);
  2071.             if (l == 0) {
  2072.                             /* Idiot supplied void key file.  Give 'im
  2073.                    what he asked for: no encryption. */
  2074.                 curotp[0] = 0;
  2075.                 l = 1;
  2076.             }
  2077.             fclose(fp);
  2078.             /* If the file is shorter than the maximum buffer
  2079.                we may need to encrypt, replicate the key until
  2080.                the buffer is filled. */
  2081.             j = l;
  2082.             k = 0;
  2083.             while (j < BUFL) {
  2084.                 curotp[j++] = curotp[k++];
  2085.                 if (k >= l) {
  2086.                 k = 0;
  2087.                 }
  2088.             }
  2089.             }
  2090.             break;
  2091. #endif
  2092.  
  2093.                 case 'P':             /* -Phost  --  Copy output to host  */
  2094.             if (!addest(op + 1)) {
  2095.             return 1;
  2096.             }
  2097.             break;
  2098.  
  2099.                 case 'Q':             /* -Q  --  Disable debug output  */
  2100.             debugging = FALSE;
  2101.             break;
  2102.  
  2103.                 case 'R':             /* -R    --  Ring: divert output to speaker */
  2104.                       /* -RTP  --  Use RTP to transmit */
  2105.                     if (ucase(op[1]) == 'T') {
  2106.             rtp = TRUE;
  2107.             } else {
  2108.             ring = TRUE;
  2109.             }
  2110.             break;
  2111.  
  2112.                 case 'S':             /* -Sn,d  --  Squelch at level n,
  2113.                             delay d milliseconds */
  2114.             if (strlen(op + 1) == 0) {
  2115.             squelch = DEFAULT_SQUELCH; /* Default squelch */
  2116.             } else {
  2117.             char *cp;
  2118.  
  2119.                         if (op[1] != ',') {
  2120.                 squelch = atoi(op + 1);
  2121.             } else {
  2122.                 squelch = DEFAULT_SQUELCH;
  2123.             }
  2124.                         cp = strchr(op + 1, ',');
  2125.             if (cp != NULL) {
  2126.                 sqdelay = 8 * atoi(cp + 1);
  2127.             }
  2128.             }
  2129.             break;
  2130.  
  2131.                 case 'T':             /* -T -- Telephone (GSM) compression */
  2132.             gsmcompress = TRUE;
  2133.             lpccompress = lpc10compress = adpcmcompress = FALSE;
  2134. #ifdef OBSOLETE
  2135.                     if (ucase(op[1]) == 'C') {
  2136.             gsm_byte_order_kludge = TRUE;
  2137.             }
  2138. #endif
  2139. #ifdef BYTE_SWAP_DEBUG
  2140.             /* This can be used if you absolutely have to communicate
  2141.                with somebody running a version prior to 6.1e on little-endian
  2142.                hardware.  This brakes the byte order of GSM packets to
  2143.                compensate for a bug in earlier versions.  Note that you
  2144.                should only set this for compatibility with old Unix
  2145.                versions--the problem this works around was never in
  2146.                the Windows version. */
  2147.                     if (ucase(op[1]) == 'D') {
  2148.             gsm_byte_order_debug = TRUE;
  2149.             }
  2150. #endif
  2151.             break;
  2152.  
  2153.                 case 'U':             /* -U  --  Print usage information */
  2154.                 case '?':             /* -?  --  Print usage information */
  2155.             usage();
  2156.             return 0;
  2157.  
  2158.                 case 'V':             /* -V  --  Use VAT protocol */
  2159.             vat = TRUE;
  2160.             if (vatid == NULL) {
  2161.             vatidl = makeVATid(&vatid, 0L);
  2162.             }
  2163.             break;
  2164.  
  2165.                 case 'W':             /* -Wfile -- Write raw audio to file */
  2166.                     audioDumpFile = fopen(op + 1, "w");
  2167.             if (audioDumpFile == NULL) {
  2168.                         perror("Cannot create raw audio dump (-w option) file");
  2169.             return 2;
  2170.             }
  2171.             break;
  2172.  
  2173. #ifdef AUDIO_DEVICE_FILE
  2174.                 case 'Y':             /* -Yindev:[ctldev] -- Specify audio input and control device file names
  2175.                                  or #open_fd. */
  2176.             devAudioInput = op + 1;
  2177.                     if (strchr(op + 1, ':') != NULL) {
  2178.                         devAudioControl = strchr(op + 1, ':') + 1;
  2179.             }
  2180.             break;
  2181. #endif
  2182.  
  2183. #ifdef CRYPTO
  2184.                 case 'Z':             /* -Z"user1 user2..."  --  Send PGP
  2185.                          encrypted session key to
  2186.                          named users */
  2187.             if (op[1] == 0) {
  2188.             curpgpkey[0] = FALSE;
  2189.             } else {
  2190.             char c[80], f[40];
  2191.             FILE *kfile;
  2192.             FILE *pipe;
  2193.             long flen;
  2194.  
  2195.                         sprintf(f, "/tmp/.SF_SKEY%d", getpid());
  2196.                         sprintf(c, "pgp -fe +nomanual +verbose=0 +armor=off %s >%s", op + 1, f);
  2197. #ifdef PGP_DEBUG
  2198.                         fprintf(stderr, "Encoding session key with: %s\n", c);
  2199. #endif
  2200.                         pipe = popen(c, "w");
  2201.             if (pipe == NULL) {
  2202.                             fprintf(stderr, "Unable to open pipe to: %s\n", c);
  2203.                 return 2;
  2204.             } else {
  2205.                 makeSessionKey(curpgpkey + 1, NULL, FALSE);
  2206. #ifdef PGP_DEBUG
  2207.                 {
  2208.                 int i;
  2209.  
  2210.                                 fprintf(stderr, "Session key:", hostname);
  2211.                 for (i = 0; i < 16; i++) {
  2212.                                     fprintf(stderr, " %02X", curpgpkey[i + 1] & 0xFF);
  2213.                 }
  2214.                                 fprintf(stderr, "\n");
  2215.                 }
  2216. #endif
  2217.                 /* The reason we start things off right with
  2218.                                "Special K" is to prevent the session key
  2219.                    (which can be any binary value) from
  2220.                                triggering PGP's detection of the file as
  2221.                    one already processed by PGP.  This causes an
  2222.                    embarrassing question when we are attempting
  2223.                    to run silent. */
  2224.                             curpgpkey[0] = 'K';
  2225.                 fwrite(curpgpkey, 17, 1, pipe);
  2226.                 curpgpkey[0] = FALSE;
  2227.                 fflush(pipe);
  2228.                 pclose(pipe);
  2229.             }
  2230.                         kfile = fopen(f, "r");
  2231.             if (kfile == NULL) {
  2232.                             fprintf(stderr, "Cannot open key file %s\n", f);
  2233.             } else {
  2234.                 fseek(kfile, 0L, 2);
  2235.                 flen = ftell(kfile);
  2236.                 rewind(kfile);
  2237. #ifdef PGP_DEBUG
  2238.                             fprintf(stderr, "PGP key buffer length: %d\n", flen);
  2239. #endif
  2240.                 if (flen > (TINY_PACKETS -
  2241.                     (sizeof(soundbuf) - BUFL))) {
  2242.                                 fprintf(stderr, "Warning: PGP key message exceeds %d packet size.\n", TINY_PACKETS);
  2243.                 }
  2244.                 if (pgpsb != NULL) {
  2245.                 free(pgpsb);
  2246.                 }
  2247.                 pgpsb = (soundbuf *) malloc(((unsigned) flen) +
  2248.                       (TINY_PACKETS - (sizeof(soundbuf) - BUFL)));
  2249.                 if (pgpsb == NULL) {
  2250.                                 fprintf(stderr, "Cannot allocate PGP sound buffer.\n");
  2251.                 fclose(kfile);
  2252.                 unlink(f);
  2253.                 return 2;
  2254.                 }
  2255.                 fread(pgpsb->buffer.buffer_val, (int) flen, 1, kfile);
  2256.                 pgpsbl = flen;
  2257.                 pgpsb->buffer.buffer_len = htonl(flen);
  2258.                 pgpsb->compression = htonl(fProtocol | fKeyPGP);
  2259. #ifdef SENDMD5
  2260.                 MD5Init(&md5c);
  2261.                 MD5Update(&md5c, pgpsb->buffer.buffer_val, pgpsb->buffer.buffer_len);
  2262.                 MD5Final(pgpsb->sendinghost, &md5c);
  2263. #else
  2264.                 strcpy(pgpsb->sendinghost, hostname);
  2265. #endif
  2266.                 fclose(kfile);
  2267.                 curpgpkey[0] = TRUE;
  2268.             }
  2269.             unlink(f);
  2270.             }
  2271.             break;
  2272. #endif
  2273.         }
  2274.     } else {
  2275.  
  2276.         /*    Check for conflicting options.    */
  2277.  
  2278.         if (rtp && vat) {
  2279.                 fprintf(stderr, "Cannot choose both -RTP and -VAT protocols simultaneously.\n");
  2280.         return 2;
  2281.         }
  2282.  
  2283.         if (rtp || vat) {
  2284. #ifdef CRYPTO
  2285.         if (curideakey[0] || curpgpkey[0] ||
  2286.             curblowfish_spec || curotp != NULL) {
  2287.                     fprintf(stderr, "Blowfish, IDEA, PGP, and Key File encryption cannot be used\n    with -RTP or -VAT protocols.\n");
  2288.             return 2;
  2289.         }
  2290. #endif
  2291.         if (compressing) {
  2292.                     fprintf(stderr, "Simple (-C) compression cannot be used with\n   -RTP or -VAT protocols.\n");
  2293.             return 2;
  2294.         }
  2295.         if (lpc10compress) {
  2296.                     fprintf(stderr, "LPC-10 (-LPC10) compression cannot be used with\n   -RTP or -VAT protocols.\n");
  2297.             return 2;
  2298.         }
  2299.         if (ring) {
  2300.                     fprintf(stderr, "Warning: ring not implemented in -RTP and -VAT protocols.\n");
  2301.         }
  2302.         }
  2303.  
  2304.         if (dests == NULL) {
  2305.         if (!addest(op)) {
  2306.             return 1;
  2307.         }
  2308.         } else {
  2309.         int ok = sendfile(op);
  2310.         if (ok != 0)
  2311.             return ok;
  2312.         sentfile++;
  2313.         }
  2314.     }
  2315.     }
  2316.  
  2317.     if (dests == NULL) {
  2318.     usage();
  2319.     } else {
  2320.     if (sentfile == 0) {
  2321.         return sendfile(NULL);
  2322.     }
  2323.     }
  2324.  
  2325.     exiting();
  2326.     gsm_destroy(gsmh);
  2327.     lpc_end();
  2328. #ifdef CRYPTO
  2329.     desdone();
  2330. #endif
  2331.     return 0;
  2332. }
  2333.